#include "pspconnect.h"


#define SERVER_PORT 49500
char name[1024];
char *buffer; // [(PLAYERS-1)*14 + 5 + NBFLAGS*10];
//extern char buffer2;
char *input = "0000000\n";

		
struct in_addr addr;
void receive(int sock);
int make_socket(uint16_t port)
{
	int sock;
	int err;
	struct sockaddr_in name;

	sock = socket(PF_INET, SOCK_STREAM, 0);
	if(sock < 0)
	{
		return -1;
	}

	name.sin_family = PF_INET;
	name.sin_port = htons(port);
	name.sin_addr = addr;
	 err = sceNetInetBind(sock, (struct sockaddr *)&name, sizeof(name));
    if (err < 0) {
        printf("\nBinding error %i\n", sceNetInetGetErrno());
    } else {
        printf("\nBinding ok\n");
    }
	return sock;
}

int send_input()
{
	int pspsend, inp;
	pspsend=100000;
	inp = InputJoyKeyTriger(0);
	if  ((inp && IN_Up) != 0) 
	{	
 
		//pspsend = send(sock, "up\n", strlen("up\n"), 0);
		//receive(sock);
		//player->posY-=2;
		input[0]='1';
	} 
	if((inp & IN_Down) != 0)
	{

		//pspsend = send(sock, "do\n", strlen("up\n"), 0);
		//receive(sock);
  		//player->posY+=2;
  		input[1]='1';
 	}
	if ((inp & IN_Left) != 0)
	{	
		//pspsend = send(sock, "le\n", strlen("up\n"), 0);
		//receive(sock);
		//player->posX-=2;
		input[2]='1';
	}
 	if ((inp & IN_Right) != 0)
 	{

		//pspsend = send(sock, "ri\n", strlen("up\n"), 0);
		//receive(sock);
		//player->posX+=2;
		input[3]='1';
	}
 	return pspsend;
}   

void receive_world(int sock)
{
	int cch;
	//int pspsend ;
	buffer = malloc(sizeof(char)*((PLAYERS-1)*14 + 5 + NBFLAGS*10));
	cch = recv(sock, (u8*)buffer, sizeof(buffer)-1, 0);
	if (cch < 0)
	{
		printf("RCV ERROR\n");
		int errnb = sceNetInetGetErrno();
		if (errnb == 11)
		{
			// recv timeout
		}
	}
	else
	{
		//successfull receive
		//printf("RECEIVED SOMETHING\n");
		buffer[cch] = '\0';
		//sceKernelDelayThread(50*1000);
		//printf("%s\n",buffer);
		//sceKernelDelayThread(50*1000);
		if (buffer[0]=='p')
		{	
			printf("P IS HERE!!!!!!\n");
			//parser(buffer);
			//printf("buffer = %s", buffer);
			strcpy(buffer2, buffer);
			//int i;
			//SDL_mutexP(buff2_mut);
			//for (i=0; i<strlen(buffer);i++) buffer2[i] = buffer[i];
			//SDL_mutexV(buff2_mut);
			//sceKernelResumeThread(thid2);
			//sceKernelSuspendThread(thid); 
			//sceKernelDelayThread(100*100);
			buffer[0]='a';
			}
		}
	free(buffer);
	
}
void receive_ping(int sock) 
{
		//char buffer[(PLAYERS-1)*14 + 5 + NBFLAGS*10];
			int cch;
			int pspsend ;
			buffer = malloc(sizeof(char)*((PLAYERS-1)*14 + 5 + NBFLAGS*10));
			cch = recv(sock, (u8*)buffer, sizeof(buffer)-1, 0);
			if (cch < 0)
			{
				printf("RCV ERROR\n");
				int errnb = sceNetInetGetErrno();
				if (errnb == 11)
				{
					// recv timeout
				}
			}
			else
			{
				//successfull receive
				//printf("RECEIVED SOMETHING\n");
				buffer[cch] = '\0';
				//sceKernelDelayThread(50*1000);
				//printf("%s\n",buffer);
				//sceKernelDelayThread(50*1000);
				if (buffer[0]=='p')
				{	
					printf("P IS HERE!!!!!!\n");
					//parser(buffer);
					//printf("buffer = %s", buffer);
					strcpy(buffer2, buffer);
					//int i;
					//SDL_mutexP(buff2_mut);
					//for (i=0; i<strlen(buffer);i++) buffer2[i] = buffer[i];
					//SDL_mutexV(buff2_mut);
					//sceKernelResumeThread(thid2);
					//sceKernelSuspendThread(thid); 
					//sceKernelDelayThread(100*100);
					buffer[0]='a';
				}
				else
				{
					if (buffer[0]=='?') 
					{
						printf("? IS HERE!!!!!!\n");
						//printf ("ping recu\n");
						pspsend = send(sock, input , strlen(input),0);
						receive_world(sock);
						//input = "0000000\n";
						//buffer[0]='a';
						//sceKernelDelayThread(300*1000);
						input[0]='0';
						input[1]='0';
						input[2]='0';
						input[3]='0';
						buffer[0]='a';
						////receive(sock);
					}
					//else if (buffer[0]!='a') printf("no understandable message\n");
					//else printf("no understandable message\n");
				}
			}
			free(buffer);
			printf("net_thread\n");
			sceKernelWakeupThread(thid2);
			sceKernelSleepThread();
              
}   



int make_socket_adr(uint16_t port, char adr[])
{
	int err;
	struct hostent *serveur;
	serveur  = gethostbyname(adr);
	int sock = socket(AF_INET, SOCK_STREAM, 0); 
	printf ("socket cree\n");

    struct sockaddr_in addrTo;
    
    addrTo.sin_family = AF_INET;
    addrTo.sin_port = htons(port);
    addrTo.sin_addr = *(struct in_addr*)serveur->h_addr;
    
    err = connect(sock,(struct sockaddr *)&addrTo, sizeof(addrTo));
    if (err < 0) {
        printf("\nConnect error %i\n", sceNetInetGetErrno());
    } else {
        printf("\nConnect ok\n");
    }
    
	return sock;
}	

/* Connect to an access point */
int connect_to_apctl(int config)
{
	int err;
	int stateLast = -1;

	/* Connect using the first profile */
	err = sceNetApctlConnect(config);
	if (err != 0)
	{
		return 0;
	}
	while (1)
	{
		int state;
		err = sceNetApctlGetState(&state);
		if (err != 0)
		{
			printf(" sceNetApctlGetState returns $%x\n", err);
			break;
		}
		if (state > stateLast)
		{
			printf("  connection state %d of 4\n", state);
			stateLast = state;
		}
		if (state >= 4)
			break;  // connected with static IP
	
		sceKernelDelayThread(50*1000); 
		// wait a little before polling again
	}
	printf(" Connected!\n");

	if(err != 0)
	{
		return 0;
	}

	return 1;
}

void com(char* host){
	make_socket_adr(SERVER_PORT, host);
	
}

int net_thread(SceSize args, void *argp)
{
	int err,socket,input, size;
	size = sizeof(struct sockaddr_in);
	int pspsend;
		do
	{
		if((err = pspSdkInetInit()))
		{
			printf("Error, could not initialise the network %08X\n", err);
			break;
		}

		if(connect_to_apctl(1))
		{
			socket = make_socket_adr(SERVER_PORT,"192.168.1.11");
			pspsend = send(socket, "hello00\n", strlen("hello00\n"), 0);
			while (TRUE && !AppExit)
    		{
   		 		
   		 			//SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0, 0, 0));
   		 			InputPoll();
   		 			input = send_input();
   		 			//drawPlayer(player);
   		 			//input = send_input(socket);
   		 			receive_ping(socket);
   		 			//SDL_Flip(screen);
    		}
			input = send(socket, "qu\n", strlen("qu\n"), 0);
		}

	}
	while(0);

	return 0;
}
